package com.thrd.basicframework.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.thrd.basicframework.R;

/**
 * @author: ${唐杰}
 * @date: 2021/3/10
 * 带指示器+自动轮播的viewPager
 */
public class ViewPageIndicator  extends FrameLayout {

    private Context context;
    private TouchViewPager mViewPager;
    private RelativeLayout.LayoutParams layoutParams;
    private RoundIndicatorView view;
    //指示器大小
    private int indicatorSize=20;
    //指示器间隔
    private int indicatorInterval=20;
    //指示器位置
    private int indicatorGravity=Gravity.CENTER_HORIZONTAL;
    //指示器位置距离下方
    private int indicatorBottomMargin=20;
    //指示器位置距离左边
    private int indicatorLeftMargin=0;
    //指示器位置距离右边
    private int indicatorRightMargin=0;
    //指示器默认颜色
    private int indicatorDefaultColor;
    //指示器选择颜色
    private int indicatorSelectedColor;

    //是否开启自动轮播
    private boolean indicatorCarousel=false;
    //轮播时长
    private int indicatorCarouselTime=3000;
    //当前显示页面数
    private int carousePosition=0;
    //总页面数
    private int adapterSize=0;

    private Handler mHandler;

    public ViewPageIndicator(@NonNull Context context) {
        this(context,null);
    }

    public ViewPageIndicator(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ViewPageIndicator(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        @SuppressLint("CustomViewStyleable")
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IndicatorView, defStyleAttr,0);
        indicatorBottomMargin = a.getDimensionPixelSize(R.styleable.IndicatorView_indicator_bottom_margin, 20);
        indicatorLeftMargin = a.getDimensionPixelSize(R.styleable.IndicatorView_indicator_left_margin, 0);
        indicatorRightMargin = a.getDimensionPixelSize(R.styleable.IndicatorView_indicator_right_margin, 0);
        indicatorGravity= a.getInt(R.styleable.IndicatorView_indicator_gravity,Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
        indicatorInterval = a.getDimensionPixelSize(R.styleable.IndicatorView_indicator_interval, 20);
        indicatorSize = a.getDimensionPixelSize(R.styleable.IndicatorView_indicator_size, 20);
        indicatorDefaultColor = a.getColor(R.styleable.IndicatorView_indicator_default_color, Color.BLACK);
        indicatorSelectedColor = a.getColor(R.styleable.IndicatorView_indicator_selected_color, Color.WHITE);
        indicatorCarousel=a.getBoolean(R.styleable.IndicatorView_indicator_carousel,false);
        indicatorCarouselTime=a.getInt(R.styleable.IndicatorView_indicator_carousel_time,3000);
        a.recycle();
        initView();
        initData();

    }

    private void initData() {
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setOnTouchChangeListener(new TouchViewPager.OnTouchChangeListener() {
            @Override
            public void onTouchEvent(MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    Log.e("ViewPageIndicator","按下");
                    stopCarousel();
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    startCarousel();
                    Log.e("ViewPageIndicator","弹起");
                }
            }
        });

        startCarousel();
    }

    private void initView() {
        mViewPager = new TouchViewPager(context);
        addView(mViewPager, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
    }


    public void setAdapter(PagerAdapter adapter){
        mViewPager.setAdapter(adapter);
        clearView();
        initIndicator(adapter);
        startCarousel();



    }

    /**
     * 初始化指示器
     * @param adapter
     */
    private void initIndicator(PagerAdapter adapter) {
        if(adapter!=null&&adapter.getCount()>0){
            adapterSize=adapter.getCount();
            RelativeLayout mLinearLayout=new RelativeLayout(context);
            for (int i=0;i<adapterSize;i++){
                RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(indicatorSize,indicatorSize);
                layoutParams.leftMargin=i*(indicatorInterval+indicatorSize);
                RoundIndicatorView view=new RoundIndicatorView(context,indicatorDefaultColor);
                view.setLayoutParams(layoutParams);
                mLinearLayout.addView(view);
            }
            layoutParams = new RelativeLayout.LayoutParams(indicatorSize,indicatorSize);
            view = new RoundIndicatorView(context,indicatorSelectedColor);
            view.setLayoutParams(layoutParams);
            mLinearLayout.addView(view);
            LayoutParams layoutParams  = (LayoutParams) mLinearLayout.getLayoutParams();
            if(layoutParams==null){
                layoutParams=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            }
            layoutParams.gravity=indicatorGravity;
            layoutParams.bottomMargin=indicatorBottomMargin;
            layoutParams.leftMargin=indicatorLeftMargin;
            layoutParams.rightMargin=indicatorRightMargin;

            addView(mLinearLayout,layoutParams);
        }else{
            adapterSize=0;
        }
    }

    /**
     * 清除指示器
     */
    private void clearView() {
        for (int i=1;i<getChildCount();i++){
            removeViewAt(i);
        }
    }

    /**
     * 跳转页面
     * @param item
     */
    public void setCurrentItem(int item){
        if(mViewPager!=null){
            stopCarousel();
            mViewPager.setCurrentItem(item);
            carousePosition=item;
            startCarousel();
        }
    }


    public int getCurrentItem(){
        return mViewPager!=null?mViewPager.getCurrentItem():0;
    }

    /**
     * 开启轮播
     */
    private void startCarousel(){
        if(adapterSize>1&&indicatorCarousel){
            stopCarousel();
            if(mHandler==null){
                mHandler=new Handler(Looper.getMainLooper());
            }
            mHandler.removeCallbacks(runnable);
            mHandler.postDelayed(runnable,indicatorCarouselTime);
            Log.e("ViewPageIndicator","定时器开启");
        }
    }
    /**
     * 关闭轮播
     */
    private void stopCarousel(){
        if(mHandler!=null){
            Log.e("ViewPageIndicator","定时器关闭");
            mHandler.removeCallbacks(runnable);
        }
    }


    public int getIndicatorSize() {
        return indicatorSize;
    }

    public void setIndicatorSize(int indicatorSize) {
        this.indicatorSize = indicatorSize;
    }

    public int getIndicatorInterval() {
        return indicatorInterval;
    }

    public void setIndicatorInterval(int indicatorInterval) {
        this.indicatorInterval = indicatorInterval;
    }

    public int getIndicatorGravity() {
        return indicatorGravity;
    }

    public void setIndicatorGravity(int indicatorGravity) {
        this.indicatorGravity = indicatorGravity;
    }

    public int getIndicatorBottomMargin() {
        return indicatorBottomMargin;
    }

    public void setIndicatorBottomMargin(int indicatorBottomMargin) {
        this.indicatorBottomMargin = indicatorBottomMargin;
    }

    public int getIndicatorLeftMargin() {
        return indicatorLeftMargin;
    }

    public void setIndicatorLeftMargin(int indicatorLeftMargin) {
        this.indicatorLeftMargin = indicatorLeftMargin;
    }

    public int getIndicatorRightMargin() {
        return indicatorRightMargin;
    }

    public void setIndicatorRightMargin(int indicatorRightMargin) {
        this.indicatorRightMargin = indicatorRightMargin;
    }

    public int getIndicatorDefaultColor() {
        return indicatorDefaultColor;
    }

    public void setIndicatorDefaultColor(int indicatorDefaultColor) {
        this.indicatorDefaultColor = indicatorDefaultColor;
    }

    public int getIndicatorSelectedColor() {
        return indicatorSelectedColor;
    }

    public void setIndicatorSelectedColor(int indicatorSelectedColor) {
        this.indicatorSelectedColor = indicatorSelectedColor;
    }

    public boolean isIndicatorCarousel() {
        return indicatorCarousel;
    }

    public void setIndicatorCarousel(boolean indicatorCarousel) {
        this.indicatorCarousel = indicatorCarousel;
    }

    public int getIndicatorCarouselTime() {
        return indicatorCarouselTime;
    }

    public void setIndicatorCarouselTime(int indicatorCarouselTime) {
        this.indicatorCarouselTime = indicatorCarouselTime;
    }

    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
           if(mViewPager!=null){
               mViewPager.setCurrentItem((carousePosition+1)>=adapterSize?carousePosition=0:++carousePosition);
               Log.e("ViewPageIndicator","carousePosition="+carousePosition);
               mHandler.removeCallbacks(runnable);
               mHandler.postDelayed(runnable,indicatorCarouselTime);
           }
        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener=new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            Log.e("Zorro", "positionOffset" +positionOffset);
            if(layoutParams!=null){
                layoutParams.leftMargin= (int) ((position*(indicatorInterval+indicatorSize))+(positionOffset*(indicatorInterval+indicatorSize)));
                view.setLayoutParams(layoutParams);
            }

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };








    /**
     * 对用户不可见
     */
    public void onFragmentPause() {
        stopCarousel();

    }

    /**
     * 对用户可见
     */
    public void onFragmentResume() {
        startCarousel();
    }

    /**
     * 结束所有状态
     */
    public void onDestroy(){
        stopCarousel();
        mHandler=null;
        if(mViewPager!=null){
            mViewPager.removeOnPageChangeListener(onPageChangeListener);
            mViewPager.setOnTouchChangeListener(null);
            mViewPager=null;
        }

    }





}
